<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
<h1>demo</h1>
<p>一个管理文件的文件服务，支持大文件上传，文件分段上传，
    对文件进行md5去重，更加节约磁盘，支持高并发，分布式，
    需自己配置eureka及gateway， 建议使用时删除“获取所有文件”接口</p>
<hr/>
<!--<input id="file" type="file" multiple webkitdirectory>-->
<input id="file" type="file" multiple>
<div id="text"></div>
<div id="progress"></div>
<hr/>
文件hashCode:<input id="hashCode">
<button id="download">下载</button>
<span id="url"></span>
<hr/>
文件hashCode:<input id="hash">
<button id="delete">删除</button>
<br/>
<video src="http://192.168.111.131:8811/8a456d5f4f85c15ec774df8710050de4.mp4"
       autoplay controls="controls" style="width: 800px;
    height: 480px;">
    您的浏览器不支持 video 标签。
</video>
<br/>
<video src="http://192.168.111.131:8811/file/download/8a456d5f4f85c15ec774df8710050de4.mp4"
       autoplay controls="controls" style="width: 800px;
    height: 480px;">
    您的浏览器不支持 video 标签。
</video>

</body>
<script src="spark-md5.js"></script>
<script>
    let ip = "http://127.0.0.1:8811";

    //删除文件
    document.getElementById("delete").onclick = function () {
        let hashCodes = document.getElementById("hash").value;
        let httpRequest = new XMLHttpRequest();
        httpRequest.open("DELETE", ip + "/file/delete/" + hashCodes);
        httpRequest.send();
    }
    //下载文件
    document.getElementById("download").onclick = function () {
        let hashCode = document.getElementById("hashCode").value;
        let url = ip + "/file/download/" + hashCode
        location.href = url;
        document.getElementById("url").innerText = url;
    }


    document.getElementById("file").onchange = async function (e) {
        let i = 0;
        for (let file of this.files) {
            let md5 = await upload(file)
            // console.log(i);
            uploadFile(file, 0, md5, 0, i)
            i++
        }
    }

    function upload(file) {
        return new Promise(resolve => {
            // let time = new Date().getTime()
            const spark = new SparkMD5.ArrayBuffer();
            let renewalSize = 104857600;
            let current = 0
            let reader = new FileReader();
            reader.readAsArrayBuffer(file.slice(current, current + renewalSize))
            reader.onload = function (e) {
                spark.append(e.target['result']);
                if (file.size <= current) {
                    // console.log("加密完成:" + (new Date().getTime() - time))
                    resolve(spark.end())
                } else {
                    current += renewalSize;
                    if (file.size <= current) {
                        current = file.size
                    }
                    reader.readAsArrayBuffer(file.slice(current, current + renewalSize))
                    document.getElementById("progress").innerText = parseInt(current / (file.size / 100))
                }
            }
        })
    }


    function uploadFile(file, fileIndex, hashCode, renewalSize, i) {
        const blob = file.slice(fileIndex, fileIndex + renewalSize);
        //上传文件
        let formData = new FormData();
        formData.append('file', blob);
        formData.append('uploadId', i);
        formData.append('hashCode', hashCode);
        formData.append('fileIndex', fileIndex);
        formData.append('size', file.size);
        let httpRequest = new XMLHttpRequest();
        httpRequest.open("POST", ip + "/file/upload");
        httpRequest.upload.addEventListener("progress", function (evt) {
            if (blob.size === file.size) {
                const progress = Math.round((evt.loaded) * 100 / evt.total);
                document.getElementById("progress").innerText = parseInt(progress + "")
            }
        }, false);
        httpRequest.onloadend = function (res) {
            if (res.target['status'] === 200) {
                if (res.target['response']) {
                    const data = JSON.parse(res.target['response']);
                    if (data['finish']) {
                        document.getElementById("text").innerText = "文件上传成功:" + this.responseText
                        document.getElementById("progress").innerText = "100"
                    } else {
                        const progress = Math.round((data['fileIndex'] / file.size) * 100);
                        document.getElementById("progress").innerText = parseInt(progress + "")
                        console.log(JSON.stringify(data) + i + "-" + hashCode)
                        uploadFile(file, data['fileIndex'], hashCode, data["renewalSize"], i)
                    }
                }
            } else {
                return false;
            }

        };
        httpRequest.send(formData);
    }
</script>
</html>
